﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Twilight.TwitterData;
using System.ComponentModel;
using Twilight.Views;
using System.Windows.Media.Imaging;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Threading;
using System.Linq;

namespace Twilight.ViewModels
{
    public class RotatingViewModel : BaseViewModel
    {
        private Tweet[] tweets;
        private DispatcherTimer timer;
        private int current = 0;

        public string FollowCount { get; private set; }
        public Tweet CurrentTweet { get; private set; }

        protected override void LoadData()
        {
            if (IsDesignTime())
            {
                CurrentTweet = new Tweet() { text = "This is some design time data for you to work with.", created_at = DateTime.Now.ToString("ddd MMM dd HH:mm:ss zzz yyyy", null), source = "code" };
            }
            else
            {
                timer = new DispatcherTimer();
                timer.Tick += new EventHandler(timer_Tick);
                timer.Interval = TimeSpan.FromSeconds(10);
            }

            base.LoadData();
        }

        protected override void UpdateTweets(Tweet[] tweets)
        {
            if (!loaded)
            {
                loaded = true;
                HookupStoryboards();               

                User u = tweets[0].user;

                FollowCount = u.followers_count.ToString();
                PropertyUpdated("FollowCount");
                Followers = string.Format("{0} followers", u.followers_count);
                PropertyUpdated("Followers");

                LoadAvatar(new Uri(u.profile_image_url));

                GoToState("Loaded");
            }

            this.tweets = tweets;
        }

        protected virtual void HookupStoryboards()
        {
            var container = FindVisualStatesContainer(RootVisual);
            if (container == null) return;

            FindStateStoryboard(container, "LoadStates", "Loaded").Completed += new EventHandler(LoadedStoryboard_Completed);
            FindStateStoryboard(container, "TweetViewStates", "Hidden").Completed += new EventHandler(fadeOutStoryboard_Completed);
        }

        public Storyboard FindStateStoryboard(FrameworkElement container, string groupName, string stateName)
        {
            Collection<VisualStateGroup> groups = (Collection<VisualStateGroup>)VisualStateManager.GetVisualStateGroups(container);

            foreach (var group in groups)
            {
                if (group.Name == groupName)
                {
                    Collection<VisualState> states = (Collection<VisualState>)group.States;
                    foreach (var state in states)
                    {
                        if (state.Name == stateName)
                        {
                            return state.Storyboard;
                        }
                    }
                }
            }

            return null;
        }

        public FrameworkElement FindVisualStatesContainer(DependencyObject parent)
        {
            var children = VisualTreeHelper.GetChildrenCount(parent);

            for (int i = 0; i < children; i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
                if (child != null && VisualStateManager.GetVisualStateGroups(child).Count > 0)
                {
                    return child;
                }
                else
                {
                    var grandchild = FindVisualStatesContainer(VisualTreeHelper.GetChild(parent, i));
                    if (grandchild != null) return grandchild;
                }
            }

            return null;
        }

        private void fadeOutStoryboard_Completed(object sender, EventArgs e)
        {
            current++;
            if (current >= tweets.Count()) current = 0;
            CurrentTweet = tweets[current];
            PropertyUpdated("CurrentTweet");

            GoToState("Shown");
        }

        private void LoadedStoryboard_Completed(object sender, EventArgs e)
        {
            CurrentTweet = tweets[0];
            PropertyUpdated("CurrentTweet");

            timer.Start();
            GoToState("Shown");
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            GoToState("Hidden");
        }

        protected virtual void GoToState(string state)
        {
            VisualStateManager.GoToState(RootVisual, state, true);
        }
    }
}
